(function ($) {
    //默认参数
    var defaluts = {
        searchName: '.ySearchSelectParts'
    };
    $.fn.extend({
        "ySearchSelectParts": function (options) {
            defaluts.searchName = options;
            var opts = $.extend({}, defaluts, options); //使用jQuery.extend 覆盖插件默认参数
            return this.each(function () {  //这里的this 就是 jQuery对象。这里return 为了支持链式调用
                initSelect(opts);
            });

        }
    });
    //初始化插件
    let productInfo = [];

    function initSelect(o) {
        $(document).click(function () {
            var thin = this;
            $(".ySearchSelectParts table").hide();
            $(".ySearchSelectParts .input-text").hide();
            $(".ySearchSelectParts .layui-form.layui-border-box.layui-table-view").hide();
            $(".ySearchSelectParts i.layui-edge").removeClass("select");
        });

        $(o.searchName + " .layui-input").click(function (event) {
            //阻止document点击事件
            event.stopPropagation();
            if ($(this).siblings(".input-text").length <= 0) {
                var str = '<div class="input-text">' +
                    '<input type="text" name="" placeholder="输入关键字" class="layui-input">' +
                    '</div>';
                $(o.searchName).append(str);
            }
            if ($(this).siblings("table").css("display") == "none") {
                let ids = $(o.searchName).attr("data-id");
                table.render({
                    elem: '#productSelectParent_' + ids,
                    id: 'productSelectParentTableId_' + ids,
                    data: productInfo,
                    url: 'product/getProductInfoByConcat',
                    cols: [[
                        {field: 'productCode', width: 120, title: '产品编码'},
                        {field: 'specificationCode', width: 120, title: '规格编码'},
                        {field: 'productCname', width: 120, title: '中文名称'},
                        {field: 'productEname', width: 120, title: '英文名称'}
                    ]],
                    height: 200
                });
                table.on('row(productSelectParentTable_' + ids + ')', function (obj) {
                    let data = obj.data;
                    let tableData = table.cache["producttableid"];
                    $.each(tableData, function (index, value) {
                        if (value.tempId == ids) {
                            data.tempId = ids;
                            tableData[index] = data;
                        }
                    });
                    table.reload('producttableid', {data: tableData});
                });
                $(this).siblings("i").addClass("select");
                $(this).siblings("table").show();
                $(this).siblings(".layui-form.layui-border-box.layui-table-view").show();
                $(this).siblings(".input-text").show();
            } else {
                $(this).siblings("i").removeClass("select");
                $(this).siblings("table").hide();
                $(this).siblings(".layui-form.layui-border-box.layui-table-view").hide();
                $(this).siblings(".input-text").hide();
            }
            $(o.searchName + " .input-text input").focus();
            $(o.searchName + " .input-text").width(605);

            //键盘监听事件
            $(o.searchName + " .input-text input").keyup(function (event) {
                if (event.keyCode != 38 && event.keyCode != 40) {
                    ySearchSelectPartsMate($(this).val(), o.searchName);
                }
            });
        });
    }

    //匹配搜索，不匹配则隐藏。
    function ySearchSelectPartsMate(value, name) {
        value = $.trim(value.toString()); // 去掉两头空格
        let ids = $(name).attr("data-id");
        let tableData = table.cache["producttableid"];
        $.each(tableData, function (index, values) {
            if (values.tempId == ids) {
                tableData[index]["productCode"] = value;
                $(".value_" + values.tempId).html(value);
            }
        });
        //模糊查询表格并刷新
        table.reload('productSelectParentTableId_' + ids, {
            where: {
                info: value
            }
        });
    }
})(window.jQuery);

(function ($) {
    //默认参数
    var defaluts = {
        searchName: '.ySearchSelect'
    };
    $.fn.extend({
        "ySearchSelect": function (options) {
            defaluts.searchName = options;
            var opts = $.extend({}, defaluts, options); //使用jQuery.extend 覆盖插件默认参数
            return this.each(function () {  //这里的this 就是 jQuery对象。这里return 为了支持链式调用
                initSelect(opts);
            });

        }
    });
    //初始化插件
    let productInfo = [];

    function initSelect(o) {
        $(document).click(function () {
            var thin = this;
            $(".ySearchSelect table").hide();
            $(".ySearchSelect .input-text").hide();
            $(".ySearchSelect .layui-form.layui-border-box.layui-table-view").hide();
            $(".ySearchSelect i.layui-edge").removeClass("select");
        });

        $(o.searchName + " .layui-input").click(function (event) {
            //阻止document点击事件
            event.stopPropagation();
            if ($(this).siblings(".input-text").length <= 0) {
                var str = '<div class="input-text">' +
                    '<input type="text" name="" placeholder="输入关键字" class="layui-input">' +
                    '</div>';
                $(o.searchName).append(str);
            }
            if ($(this).siblings("table").css("display") == "none") {
                let ids = $(o.searchName).attr("data-id");
                table.render({
                    elem: '#productcodeselect_' + ids,
                    id: 'productcodeselecttableid_' + ids,
                    data: productInfo,
                    url: 'product/getSpecPartsInfoByConcat',
                    cols: [[
                        {field: 'productCode', width: 120, title: '产品编码'},
                        {field: 'specificationCode', width: 120, title: '规格编码'},
                        {field: 'productCname', width: 120, title: '中文名称'},
                        {field: 'productEname', width: 120, title: '英文名称'}
                    ]],
                    height: 200
                });
                table.on('row(productcodeselecttable_' + ids + ')', function (obj) {
                    let data = obj.data;
                    let tableData = table.cache["productsatableid"];
                    let tempIds = [];
                    $.each(tableData, function (index, value) {
                        if(!isEmpty(value["id"])){
                            if(tempIds.indexOf(value["id"]) === -1){
                                tempIds.push(value["id"]);
                            }else {
                                //存在相同配件
                                layer.msg("所选配件已存在！", {icon: 5});
                                return false;
                            }
                        }
                        if (value.tempId == ids) {
                            if(tempIds.indexOf(data["id"]) === -1){
                                tempIds.push(value["id"]);
                            }else {
                                //存在相同配件
                                layer.msg("所选配件已存在！", {icon: 5});
                                return false;
                            }
                            data.tempId = ids;
                            tableData[index] = data;
                        }
                    });
                    table.reload('productsatableid', {data: tableData});
                });
                $(this).siblings("i").addClass("select");
                $(this).siblings("table").show();
                $(this).siblings(".layui-form.layui-border-box.layui-table-view").show();
                $(this).siblings(".input-text").show();
            } else {
                $(this).siblings("i").removeClass("select");
                $(this).siblings("table").hide();
                $(this).siblings(".layui-form.layui-border-box.layui-table-view").hide();
                $(this).siblings(".input-text").hide();
            }
            $(o.searchName + " .input-text input").focus();
            $(o.searchName + " .input-text").width(605);

            //键盘监听事件
            $(o.searchName + " .input-text input").keyup(function (event) {
                if (event.keyCode != 38 && event.keyCode != 40) {
                    ySearchSelectMate($(this).val(), o.searchName);
                }
            });
        });
    }

    //匹配搜索，不匹配则隐藏。
    function ySearchSelectMate(value, name) {
        value = $.trim(value.toString()); // 去掉两头空格
        let ids = $(name).attr("data-id");
        let tableData = table.cache["productsatableid"];
        $.each(tableData, function (index, values) {
            if (values.tempId == ids) {
                tableData[index]["productCode"] = value;
                $(".value_" + values.tempId).html(value);
            }
        });
        //模糊查询表格并刷新
        table.reload('productcodeselecttableid_' + ids, {
            where: {
                productCode: value
            }
        });
    }
})(window.jQuery);

var layer = layui.layer //弹层
    , table = layui.table //表格
form = layui.form, $ = layui.jquery;

let cataCodeName = "成品目录";
let cataCode = "CPMU001";

let customsCode = [];
layer.ready(function () {
    //获取海关编码信息
    $.ajax({
        url:"offer/getCustomsCode",
        success:function(data){
            if(data.status == 200){
                customsCode = data.data;
            }
        }
    });
});

//---产品列表
let productData = [];
table.render({
    elem: '#productselect'
    , data: productData
    , toolbar: '#producttoolbar'
    , cols: [[
        , {field: 'productCode', title: '产品编码', templet: '#productSelectParent', style: "color:#009688"}
        , {field: 'specificationCode', title: '规格编码', sort: true}
        , {field: 'specificationExplanation', title: '规格说明', sort: true}
        , {field: 'productCname', title: '中文名称', sort: true}
        , {field: 'productEname', title: '英文名称', sort: true}
        , {field: 'productCdesc', title: '中文描述', sort: true}
        , {field: 'productEdesc', title: '英文描述', sort: true}
    ]]
    , id: 'producttableid'
    , page: false
    , height: 350
    , done: function (res, curr, count) {
        $(".layui-table select").parent(".layui-table-cell").css('overflow', 'visible')
        $(".layui-form-select").parents(".layui-table-cell").css('overflow', 'visible')
        for (var i = 0; i < res.data.length; i++) {
            let tempId = res.data[i].tempId;
            let classs = ".y_" + tempId;
            $(classs).ySearchSelectParts(classs);
        }
    }
});

//产品新增
table.on('toolbar(producttable)', function (obj) {
    switch (obj.event) {
        case 'new':
            let oldData = table.cache["producttableid"];
            if (oldData && oldData.length >= 1) {
                layer.msg('最多只能选择一条产品！');
                return false
            }
            let tempId = GenNonDuplicateID(3) + (oldData.length + 1);
            let newData = {
                "tempId": tempId,
                "productCode": "",
                "specificationCode": "",
                "specificationExplanation": "",
                "productCname": "",
                "productEname": "",
                "productCdesc": "",
                "productEdesc": ""
            };
            oldData.push(newData);
            table.reload('producttableid', {data: oldData});
            break;
    };
});

//获取配件数据
let specData = [];
table.render({
    elem: '#productsaselect'
    , data: specData
    , toolbar: '#productsatoolbar'
    , cols: [[
        , {field: 'productCode', title: '产品编码', templet: '#productcodeselect', style: "color:#009688"}
        , {field: 'specificationCode', title: '规格编码', sort: true}
        , {field: 'specificationExplanation', title: '规格说明', sort: true}
        , {field: 'productCname', title: '中文名称', sort: true}
        , {field: 'productEname', title: '英文名称', sort: true}
        , {field: 'productCdesc', title: '中文描述', sort: true}
        , {field: 'productEdesc', title: '英文描述', sort: true}
        , {fixed: 'right', width: 150, align: 'center', toolbar: '#productsaup', title: '操作'}
    ]]
    , id: 'productsatableid'
    , page: false
    , height: 400
    , done: function (res, curr, count) {
        $(".layui-table select").parent(".layui-table-cell").css('overflow', 'visible')
        $(".layui-form-select").parents(".layui-table-cell").css('overflow', 'visible')
        for (var i = 0; i < res.data.length; i++) {
            let tempId = res.data[i].tempId;
            let classs = ".y_" + tempId;
            $(classs).ySearchSelect(classs);
        }
    }
});


//产品配件新增、删除
table.on('toolbar(productsatable)', function (obj) {
    switch (obj.event) {
        case 'new':
            let oldData = table.cache["productsatableid"];
            let tempId = GenNonDuplicateID(3) + (oldData.length + 1);
            let newData = {
                "tempId": tempId,
                "productCode": "",
                "specificationCode": "",
                "specificationExplanation": "",
                "productCname": "",
                "productEname": "",
                "productCdesc": "",
                "productEdesc": ""
            };
            oldData.push(newData);
            table.reload('productsatableid', {data: oldData});
            break;
    };
});

//配件单个删除
table.on('tool(productsatable)', function (obj) {
    let data = obj.data;
    let oldData = table.cache["productsatableid"];
    if (obj.event === 'delet') {
        layer.confirm('确认删除？', confirmInfo(3, 6), function (index) {
            for (let i in oldData) {
                if (oldData[i].tempId == data.tempId) {
                    oldData.splice(i, 1);
                    table.reload('productsatableid', {data: oldData});
                    break;
                }
            }
            layer.msg("删除成功", {icon: 6});
            layer.close(index);
        });
    }
});

//监听合并
form.on('submit(form-save)', function (data) {
    //产品信息
    let selectProductData = table.cache["producttableid"];
    let selectProductFlag = false;
    if (selectProductData && selectProductData.length == 1) {
        //产品数据只能一条
        selectProductFlag = true;
    }
    //配件信息
    let selectPartsData = table.cache["productsatableid"];
    let selectPartsFlag = false;
    if (selectPartsData && selectPartsData.length > 0) {
        //配件数据一条或多条
        selectPartsFlag = true;
    }
    if (selectProductFlag && selectPartsFlag) {
        if (cataCode == "") {
            layer.msg("请选择产品目录");
            return false;
        }
        //主产品ID
        let id = selectProductData[0]["id"];
        //主产品编码
        let productCode = selectProductData[0]["productCode"];
        //规格编码
        let specCode = selectProductData[0]["specificationCode"];
        let margeInfo = {
            id : id,
            productCode: productCode,
            specCode : specCode
        }
        let partsList = [];
        for (let i in selectPartsData) {
            //选择的配件id
            let partsId = selectPartsData[i]["id"];
            //选择的配件产品编码
            let partsProductCode = selectPartsData[i]["productCode"];
            //选择的配件规格编码
            let partsSpec = selectPartsData[i]["specificationCode"];
            let partsRes = {
                partsId : partsId,
                partsProductCode : partsProductCode,
                partsSpec : partsSpec
            }
            partsList.push(partsRes);
        }
        margeInfo["specMargeList"] = partsList;
        let margeData = [];
        $.ajax({
            type:"POST",
            dataType:"json",
            contentType: 'application/json',
            data: JSON.stringify(margeInfo),
            url:"productmaininfo/getMargeAndSaveData",
            async: false,
            success:function(res){
                if(res.status == 200){
                    margeData = res.data;
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
            }
        });
        //产品明细数据
        let oldData =  parent.table.cache["storageproductstableid"];
        //交货日期
        let deliveryDate = parent.$("#carryTime").val();
        if(isEmpty(deliveryDate)){
            let currentDate = getNowFormatDate(1);
            deliveryDate = currentDate;
        }
        //产品信息
        let newProductData = margeData["mainInfo"];
        //图片
        let imgList = JSON.parse(newProductData.img);
        let img = "";
        if(!isEmpty(imgList)){
            img = imgList[0];
        }
        //规格信息
        let newSpecData = margeData["specList"];
        let tempId = GenNonDuplicateID(3);
        let newProduct = {
            "tempId" : tempId,
            "img" : img,
            "productCode" : newProductData["code"],
            "specificationCode" : newSpecData[0]["code"],
            "productEname" : newProductData["englishName"],
            "productCdesc" : newSpecData[0]["chinaRemark"],
            "productEdesc" : newSpecData[0]["englishRemark"],
            "productNum" : 0,
            "productUnitCode" : newSpecData[0]["dw"],
            "unitPrice" : 0,
            "moneySubtotal" : 0,
            "deliveryDate" : deliveryDate,
            "specificationExplanation" : newSpecData[0]["ge"],
            "clientProductNo" : newProductData["customerCode"],
            "productCname" : newProductData["chinaName"],
            "color" : newSpecData[0]["colour"],
            "customsCode" : newProductData["hgCode"],
            "outerPackingLong" : newSpecData[0]["wbzc"],
            "outerPackingWide" : newSpecData[0]["wbzk"],
            "outerPackingHeight" : newSpecData[0]["wbzg"],
            "outerPackingExplain" : newSpecData[0]["bzsm"]
        }
        if(!isEmpty(newProductData["hgCode"])){
            for(let i in customsCode){
                if(customsCode[i].code == newProductData["hgCode"]){
                    //报关品名
                    newProduct["nameCustomsDeclaration"] = customsCode[i].name;
                    //英文品名
                    newProduct["englishProductName"] = customsCode[i].englishName;
                    //报关单位
                    newProduct["customsDeclarationUnit"] = customsCode[i].unitOfQuantity;
                    //进口关税
                    newProduct["importTariffs"] = customsCode[i].importTariff;
                    //退税率
                    newProduct["taxRebateRate"] = customsCode[i].taxRate;
                    //增值税率
                    newProduct["vatRate"] = customsCode[i].vatRate;
                    break;
                }
            }
        }
        //配件信息
        let newPartsList = margeData["partsList"];
        let partsData = [];
        for(let i in newPartsList){
            let partTempId = GenNonDuplicateID(3) + (i+1);
            let newParts = {
                "tempId" : partTempId,
                "parentTempId" : tempId,
                "partsCode" : newPartsList[i]["productCode"],
                "specNo" : newPartsList[i]["fjCode"],
                "proportionFinishedProducts" : newPartsList[i]["cpbl"],
                "partsFinishedProducts" : newPartsList[i]["pjbl"],
                "partsAmount" : 0,
                "productCname" : newPartsList[i]["chinaname"],
                "productEname" : newPartsList[i]["englishname"],
                "grossWeight" : newPartsList[i]["mz"],
                "netWeight" : newPartsList[i]["jz"],
                "bulk" : newPartsList[i]["tj"]
            }
            partsData.push(newParts);
        }
        newProduct["partsList"] = partsData;

        oldData.push(newProduct);
        parent.table.reload("storageproductstableid",{data : oldData, limit : oldData.length});

        //执行接口
        layer.msg("保存成功", {icon: 6});
        setTimeout(function () {
            //保存成功则关闭此页面
            let index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        },1000)
        return false;
    } else {
        layer.msg('请选择产品和配件进行合并');
        return false;
    }
    return false;
});

//关闭
$("#shutdown").on('click', function () {
    let index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
})

//生成临时id
function GenNonDuplicateID(randomLength) {
    return Number(Math.random().toString().substr(3, randomLength) + Date.now()).toString(36)
}

//字段是否为空或者零
function isEmpty(obj) {
    if (typeof obj == "undefined" || obj == null || obj == "" || obj == 0) {
        return true;
    } else {
        return false;
    }
}

function isNumber(val) {
    let regPos = /^\d+(\.\d+)?$/; //非负浮点数
    let regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if (regPos.test(val) || regNeg.test(val)) {
        return true;
    } else {
        return false;
    }
}

//提示信息渲染
function confirmInfo(icon, anim) {
    let data = {
        icon: icon,
        title: "提示",
        offset: "auto",
        skin: 'layui-layer-molv',
        anim: anim
    }
    return data;
}

//时间处理 获取当前时间type:1 yyyy-MM-dd type:2 yyyyMMdd+毫秒
function getNowFormatDate(type) {
    let date = new Date();
    let separator = "-";
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    if(1 == type){
        let currentDate = year + separator + month + separator + strDate;
        return currentDate;
    }else if(2 == type){
        let second = date.getMilliseconds().toString();
        if(second.length < 3){
            if(second.length == 1){
                second = "0" + "0" + second;
            }else {
                second = "0" + second;
            }
        }
        let currentDate = year.toString() + month.toString() + strDate.toString() + second;
        return currentDate;
    }

}

